package com.styletransfer.service;

import com.styletransfer.exception.BusinessException;
import com.styletransfer.mapper.StyleMapper;
import com.styletransfer.mapper.UserMapper;
import com.styletransfer.mapper.WorkMapper;
import com.styletransfer.model.*;
import com.styletransfer.service.OssService;
import com.styletransfer.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

/**
 * 作品服务类
 *
 * 这个类负责处理与作品相关的业务逻辑，包括作品的创建、更新、查询等。
 * 作品是用户使用风格转换功能生成的图片结果。
 */
@Service
public class WorkService {

    @Autowired
    private WorkMapper workMapper;

    @Autowired
    private StyleMapper styleMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OssService ossService;

    @Autowired
    private NotificationService notificationService;

    /**
     * 创建作品
     *
     * @param work 作品对象
     * @param originalImage 原始图片
     * @param resultImage 结果图片
     * @return API响应
     */
    @Transactional
    public ApiResponse<Work> createWork(Work work, MultipartFile originalImage, MultipartFile resultImage) {
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();
        work.setUserId(userId);

        // 检查风格是否存在，并增加风格使用次数
        if (work.getStyleId() != null && !work.getStyleId().isEmpty()) {
            // 解析风格ID字符串，验证每个风格ID并增加使用次数
            String[] styleIdArray = work.getStyleId().split(",");
            for (String styleIdStr : styleIdArray) {
                try {
                    Long styleId = Long.parseLong(styleIdStr.trim());
                    // 检查风格是否存在
                    if (styleMapper.findById(styleId) == null) {
                        throw new BusinessException("风格ID不存在: " + styleId);
                    }
                    // 增加风格使用次数
                    styleMapper.incrementUseCount(styleId);
                } catch (NumberFormatException e) {
                    throw new BusinessException("风格ID格式不正确: " + styleIdStr);
                }
            }
        }

        // 上传原始图片
        if (originalImage != null && !originalImage.isEmpty()) {
            String originalImagePath = ossService.uploadFile(originalImage, "works/original");
            work.setOriginalImage(originalImagePath);
        } else {
            throw new BusinessException("原始图片不能为空");
        }

        // 上传结果图片
        if (resultImage != null && !resultImage.isEmpty()) {
            String resultImagePath = ossService.uploadFile(resultImage, "works/result");
            work.setResultImage(resultImagePath);
        } else {
            throw new BusinessException("结果图片不能为空");
        }

        // 设置默认值
        work.setLikeCount(0);
        work.setCommentCount(0);
        work.setViewCount(0);
        work.setCreateTime(new Date());
        work.setUpdateTime(new Date());
        work.setStatus(1); // 1:正常, 0:删除

        // 如果没有设置是否公开，默认为公开
        if (work.getIsPublic() == null) {
            work.setIsPublic(1); // 1:公开, 0:私有
        }

        // 插入作品
        workMapper.insert(work);

        // 创建新作品通知（如果是公开作品）
        if (work.getIsPublic() == 1) {
            notificationService.createNewWorkNotification(work.getId(), work.getTitle(), userId);
        }

        return ApiResponse.success(work);
    }

    /**
     * 更新作品
     *
     * @param work 作品对象
     * @return API响应
     */
    public ApiResponse<Work> updateWork(Work work) {
        // 检查作品是否存在
        Work existingWork = workMapper.findById(work.getId());
        if (existingWork == null) {
            throw new BusinessException("作品不存在");
        }

        // 检查是否有权限修改
        if (!isAdmin() && !existingWork.getUserId().equals(getCurrentUserId())) {
            throw new BusinessException("没有权限修改此作品");
        }

        // 设置不可修改的字段
        work.setUserId(existingWork.getUserId());
        work.setStyleId(existingWork.getStyleId());
        work.setOriginalImage(existingWork.getOriginalImage());
        work.setResultImage(existingWork.getResultImage());
        work.setLikeCount(existingWork.getLikeCount());
        work.setCommentCount(existingWork.getCommentCount());
        work.setViewCount(existingWork.getViewCount());
        work.setCreateTime(existingWork.getCreateTime());
        work.setStatus(existingWork.getStatus());
        work.setUpdateTime(new Date());

        // 更新作品
        workMapper.update(work);

        return ApiResponse.success(work);
    }

    /**
     * 删除作品
     *
     * @param id 作品ID
     * @return API响应
     */
    @Transactional
    public ApiResponse<Void> deleteWork(Long id) {
        // 检查作品是否存在
        Work work = workMapper.findById(id);
        if (work == null) {
            throw new BusinessException("作品不存在");
        }

        // 检查是否有权限删除
        if (!isAdmin() && !work.getUserId().equals(getCurrentUserId())) {
            throw new BusinessException("没有权限删除此作品");
        }

        // 删除图片
        if (work.getOriginalImage() != null && !work.getOriginalImage().isEmpty()) {
            ossService.deleteFile(work.getOriginalImage());
        }
        if (work.getResultImage() != null && !work.getResultImage().isEmpty()) {
            ossService.deleteFile(work.getResultImage());
        }

        // 更新作品状态为已删除
        workMapper.updateStatus(id, 0);

        return ApiResponse.success();
    }

    /**
     * 根据ID查询作品
     *
     * @param id 作品ID
     * @return API响应
     */
    public ApiResponse<Work> findById(Long id) {
        try {
            Work work = workMapper.findById(id);
            if (work == null) {
                return ApiResponse.error("作品不存在");
            }

            // 增加浏览次数
            workMapper.incrementViewCount(id);

            // 设置用户信息
            if (work.getUserId() != null) {
                work.setUser(userMapper.findById(work.getUserId()));
            }

            // 设置风格标签
            if (work.getStyleId() != null && !work.getStyleId().isEmpty()) {
                List<String> tags = new ArrayList<>();
                String[] styleIdArray = work.getStyleId().split(",");
                for (String styleIdStr : styleIdArray) {
                    try {
                        Long styleId = Long.valueOf(styleIdStr.trim());
                        Style style = styleMapper.findById(styleId);
                        if (style != null) {
                            tags.add(style.getName());
                        }
                    } catch (NumberFormatException e) {
                        // 忽略无效的风格ID
                    }
                }
                work.setTags(tags);
            }

//            // 查询当前用户是否点赞
//            if (SecurityContextHolder.getContext().getAuthentication() != null) {
//                Long userId = getCurrentUserId();
//                if (userId != null) {
//                    work.setIsLiked(workMapper.isLiked(userId, id) > 0);
//                }
//            }

            return ApiResponse.success(work);
        } catch (Exception e) {
            return ApiResponse.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 查询用户的作品
     *
     * @param userId 用户ID
     * @return API响应
     */
    public ApiResponse<List<Work>> findByUser(Long userId) {
        try {
            List<Work> works = workMapper.findByUser(userId);

            // 设置用户信息和风格标签
            for (Work work : works) {
                if (work.getUserId() != null) {
                    work.setUser(userMapper.findById(work.getUserId()));
                }

                // 设置风格标签
                if (work.getStyleId() != null && !work.getStyleId().isEmpty()) {
                    List<String> tags = new ArrayList<>();
                    String[] styleIdArray = work.getStyleId().split(",");
                    for (String styleIdStr : styleIdArray) {
                        try {
                            Long styleId = Long.valueOf(styleIdStr.trim());
                            Style style = styleMapper.findById(styleId);
                            if (style != null) {
                                tags.add(style.getName());
                            }
                        } catch (NumberFormatException e) {
                            // 忽略无效的风格ID
                        }
                    }
                    work.setTags(tags);
                }
            }

            return ApiResponse.success(works);
        } catch (Exception e) {
            return ApiResponse.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询用户的作品
     *
     * @param userId 用户ID
     * @param pageRequest 分页请求
     * @return API响应
     */
    public ApiResponse<PageResponse<Work>> findByUserPage(Long userId, PageRequest pageRequest, String filter) {
        try {
            // 计算偏移量
            Integer offset = (pageRequest.getPageNum() - 1) * pageRequest.getPageSize();

            // 查询作品列表
            List<Work> works = workMapper.findByUserPage(userId, offset, pageRequest.getPageSize());

            // 查询总数
            Long total = workMapper.countByUser(userId);

            // 构建分页响应
            PageResponse<Work> pageResponse = new PageResponse<>(works, total, pageRequest.getPageNum(), pageRequest.getPageSize());

            return ApiResponse.success(pageResponse);
        } catch (Exception e) {
            return ApiResponse.error("查询失败");
        }
    }

    /**
     * 查询公开的作品
     *
     * @return API响应
     */
    public ApiResponse<List<Work>> findPublic() {
        try {
            List<Work> works = workMapper.findPublic();

            // 设置用户信息和风格标签
            for (Work work : works) {
                if (work.getUserId() != null) {
                    work.setUser(userMapper.findById(work.getUserId()));
                }

                // 设置风格标签
                if (work.getStyleId() != null && !work.getStyleId().isEmpty()) {
                    List<String> tags = new ArrayList<>();
                    String[] styleIdArray = work.getStyleId().split(",");
                    for (String styleIdStr : styleIdArray) {
                        try {
                            Long styleId = Long.valueOf(styleIdStr.trim());
                            Style style = styleMapper.findById(styleId);
                            if (style != null) {
                                tags.add(style.getName());
                            }
                        } catch (NumberFormatException e) {
                            // 忽略无效的风格ID
                        }
                    }
                    work.setTags(tags);
                }
            }

            return ApiResponse.success(works);
        } catch (Exception e) {
            return ApiResponse.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 查询热门作品
     *
     * @param limit 限制数
     * @return API响应
     */
    public ApiResponse<List<Work>> findHot(Integer limit) {
        try {
            List<Work> works = workMapper.findHot(limit);

            // 设置用户信息和风格标签
            for (Work work : works) {
                if (work.getUserId() != null) {
                    work.setUser(userMapper.findById(work.getUserId()));
                }

                // 设置风格标签
                if (work.getStyleId() != null && !work.getStyleId().isEmpty()) {
                    List<String> tags = new ArrayList<>();
                    String[] styleIdArray = work.getStyleId().split(",");
                    for (String styleIdStr : styleIdArray) {
                        try {
                            Long styleId = Long.valueOf(styleIdStr.trim());
                            Style style = styleMapper.findById(styleId);
                            if (style != null) {
                                tags.add(style.getName());
                            }
                        } catch (NumberFormatException e) {
                            // 忽略无效的风格ID
                        }
                    }
                    work.setTags(tags);
                }
            }

            return ApiResponse.success(works);
        } catch (Exception e) {
            return ApiResponse.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 查询最新作品
     *
     * @param limit 限制数
     * @return API响应
     */
    public ApiResponse<List<Work>> findLatest(Integer limit) {
        try {
            List<Work> works = workMapper.findLatest(limit);

            // 设置用户信息和风格标签
            for (Work work : works) {
                if (work.getUserId() != null) {
                    work.setUser(userMapper.findById(work.getUserId()));
                }

                // 设置风格标签
                if (work.getStyleId() != null && !work.getStyleId().isEmpty()) {
                    List<String> tags = new ArrayList<>();
                    String[] styleIdArray = work.getStyleId().split(",");
                    for (String styleIdStr : styleIdArray) {
                        try {
                            Long styleId = Long.valueOf(styleIdStr.trim());
                            Style style = styleMapper.findById(styleId);
                            if (style != null) {
                                tags.add(style.getName());
                            }
                        } catch (NumberFormatException e) {
                            // 忽略无效的风格ID
                        }
                    }
                    work.setTags(tags);
                }
            }

            return ApiResponse.success(works);
        } catch (Exception e) {
            return ApiResponse.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 根据风格查询作品
     *
     * @param styleId 风格ID
     * @return API响应
     */
    public ApiResponse<List<Work>> findByStyle(Long styleId) {

        // 检查风格是否存在
        if (styleMapper.findById(styleId) == null) {
            throw new BusinessException("风格不存在");
        }

        try {
            List<Work> works = workMapper.findByStyle(styleId);

            // 设置用户信息和风格标签
            for (Work work : works) {
                if (work.getUserId() != null) {
                    work.setUser(userMapper.findById(work.getUserId()));
                }

                // 设置风格标签
                if (work.getStyleId() != null && !work.getStyleId().isEmpty()) {
                    List<String> tags = new ArrayList<>();
                    String[] styleIdArray = work.getStyleId().split(",");
                    for (String styleIdStr : styleIdArray) {
                        try {
                            Long styleId2 = Long.valueOf(styleIdStr.trim());
                            Style style = styleMapper.findById(styleId2);
                            if (style != null) {
                                tags.add(style.getName());
                            }
                        } catch (NumberFormatException e) {
                            // 忽略无效的风格ID
                        }
                    }
                    work.setTags(tags);
                }
            }

            return ApiResponse.success(works);
        } catch (Exception e) {
            return ApiResponse.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询作品
     *
     * @param pageRequest 分页请求
     * @return 分页响应
     */
    public PageResponse<Work> findByPage(PageRequest pageRequest) {
        // 计算偏移量
        Integer offset = (pageRequest.getPageNum() - 1) * pageRequest.getPageSize();

        // 查询数据
        List<Work> works = workMapper.findByPage(offset, pageRequest.getPageSize());

        // 设置用户信息和风格标签
        for (Work work : works) {
            if (work.getUserId() != null) {
                work.setUser(userMapper.findById(work.getUserId()));
            }

            // 设置风格标签
            if (work.getStyleId() != null && !work.getStyleId().isEmpty()) {
                List<String> tags = new ArrayList<>();
                String[] styleIdArray = work.getStyleId().split(",");
                for (String styleIdStr : styleIdArray) {
                    try {
                        Long styleId = Long.valueOf(styleIdStr.trim());
                        Style style = styleMapper.findById(styleId);
                        if (style != null) {
                            tags.add(style.getName());
                        }
                    } catch (NumberFormatException e) {
                        // 忽略无效的风格ID
                    }
                }
                work.setTags(tags);
            }
        }

        Long total = workMapper.count();

        // 构建分页响应
        PageResponse<Work> pageResponse = new PageResponse<>();
        pageResponse.setPageNum(pageRequest.getPageNum());
        pageResponse.setPageSize(pageRequest.getPageSize());
        pageResponse.setTotal(total);
        pageResponse.setList(works);

        return pageResponse;
    }

    /**
     * 根据风格ID分页查询作品
     *
     * @param styleId 风格ID（逗号分隔的字符串）
     * @param pageRequest 分页请求
     * @return 分页响应
     */
    public PageResponse<Work> findByStylePage(String styleId, PageRequest pageRequest) {
        // 处理风格ID
        List<Long> styleIds = new ArrayList<>();
        if (styleId != null && !styleId.isEmpty()) {
            String[] styleIdArray = styleId.split(",");
            for (String id : styleIdArray) {
                try {
                    styleIds.add(Long.valueOf(id.trim()));
                } catch (NumberFormatException e) {
                    throw new BusinessException("风格ID格式不正确: " + id);
                }
            }
        }

        // 计算偏移量
        Integer offset = (pageRequest.getPageNum() - 1) * pageRequest.getPageSize();

        // 查询数据
        List<Work> works;
        Long total;
        if (styleIds.isEmpty()) {
            works = workMapper.findByPage(offset, pageRequest.getPageSize());
            total = workMapper.count();
        } else if (styleIds.size() == 1) {
            works = workMapper.findByStylePage(styleIds.get(0), offset, pageRequest.getPageSize());
            total = workMapper.countByStyle(styleIds.get(0));
        } else {
            works = workMapper.findByStylesPage(styleIds, offset, pageRequest.getPageSize());
            total = workMapper.countByStyles(styleIds);
        }

        // 设置用户信息和风格标签
        for (Work work : works) {
            if (work.getUserId() != null) {
                work.setUser(userMapper.findById(work.getUserId()));
            }

            // 设置风格标签
            if (work.getStyleId() != null && !work.getStyleId().isEmpty()) {
                List<String> tags = new ArrayList<>();
                String[] styleIdArray = work.getStyleId().split(",");
                for (String styleIdStr : styleIdArray) {
                    try {
                        Long styleId2 = Long.valueOf(styleIdStr.trim());
                        Style style = styleMapper.findById(styleId2);
                        if (style != null) {
                            tags.add(style.getName());
                        }
                    } catch (NumberFormatException e) {
                        // 忽略无效的风格ID
                    }
                }
                work.setTags(tags);
            }
        }

        // 构建分页响应
        PageResponse<Work> pageResponse = new PageResponse<>();
        pageResponse.setPageNum(pageRequest.getPageNum());
        pageResponse.setPageSize(pageRequest.getPageSize());
        pageResponse.setTotal(total);
        pageResponse.setList(works);

        return pageResponse;
    }

    /**
     * 分页查询作品（支持关键词搜索）
     *
     * @param pageRequest 分页请求
     * @param keyword 关键词
     * @return 分页响应
     */
    public PageResponse<Work> findByPage(PageRequest pageRequest, String keyword) {
        // 计算偏移量
        Integer offset = (pageRequest.getPageNum() - 1) * pageRequest.getPageSize();

        // 查询数据
        List<Work> works;
        Long total;

        if (keyword != null && !keyword.trim().isEmpty()) {
            // 有关键词，执行关键词搜索
            works = workMapper.findByKeyword(keyword.trim(), offset, pageRequest.getPageSize());
            total = workMapper.countByKeyword(keyword.trim());
        } else {
            // 无关键词，执行普通分页查询
            works = workMapper.findByPage(offset, pageRequest.getPageSize());
            total = workMapper.count();
        }

        // 设置用户信息和风格标签
        for (Work work : works) {
            if (work.getUserId() != null) {
                work.setUser(userMapper.findById(work.getUserId()));
            }

            // 设置风格标签
            if (work.getStyleId() != null && !work.getStyleId().isEmpty()) {
                List<String> tags = new ArrayList<>();
                String[] styleIdArray = work.getStyleId().split(",");
                for (String styleIdStr : styleIdArray) {
                    try {
                        Long styleId = Long.valueOf(styleIdStr.trim());
                        Style style = styleMapper.findById(styleId);
                        if (style != null) {
                            tags.add(style.getName());
                        }
                    } catch (NumberFormatException e) {
                        // 忽略无效的风格ID
                    }
                }
                work.setTags(tags);
            }
        }

        // 构建分页响应
        PageResponse<Work> pageResponse = new PageResponse<>();
        pageResponse.setPageNum(pageRequest.getPageNum());
        pageResponse.setPageSize(pageRequest.getPageSize());
        pageResponse.setTotal(total);
        pageResponse.setList(works);

        return pageResponse;
    }

    /**
     * 获取相似作品
     *
     * @param workId 作品ID
     * @return 相似作品列表
     */
    public ApiResponse<List<Work>> findSimilarWorks(Long workId) {
        try {
            // 1. 获取原作品信息
            Work work = workMapper.findById(workId);
            if (work == null) {
                return ApiResponse.error("作品不存在");
            }

            // 2. 获取相似作品（基于相同风格或关键词）
            List<Work> similarWorks = new ArrayList<>();

            // 2.1 如果有风格ID，根据风格查找相似作品
            if (work.getStyleId() != null) {
                try {
                    // 处理可能包含多个风格ID的情况
                    String[] styleIdStrArray = work.getStyleId().split(",");
                    List<Long> styleIds = new ArrayList<>();

                    // 转换所有有效的风格ID
                    for (String styleIdStr : styleIdStrArray) {
                        try {
                            styleIds.add(Long.valueOf(styleIdStr.trim()));
                        } catch (NumberFormatException e) {
                            // 忽略无效的风格ID
                            Logger.getLogger(WorkService.class.getName()).warning("Invalid style ID: " + styleIdStr);
                        }
                    }

                    // 如果有有效的风格ID，查询相似作品
                    if (!styleIds.isEmpty()) {
                        List<Work> styleWorks = workMapper.findByStyleIds(styleIds, 10);
                        // 过滤掉当前作品
                        styleWorks.removeIf(w -> w.getId().equals(workId));
                        similarWorks.addAll(styleWorks);
                    }
                } catch (Exception e) {
                    // 如果处理过程中出现任何错误，记录日志并继续其他推荐逻辑
                    Logger.getLogger(WorkService.class.getName()).warning("Error processing style IDs: " + work.getStyleId() + ", error: " + e.getMessage());
                }
            }

            // 2.2 如果仍然不足5个，获取最新作品
            if (similarWorks.size() < 5) {
                List<Work> latestWorks = workMapper.findLatest(10);
                // 过滤掉当前作品和已添加的作品
                List<Work> finalSimilarWorks = similarWorks;
                latestWorks.removeIf(w -> w.getId().equals(workId) || finalSimilarWorks.contains(w));
                // 只添加需要的数量
                int neededCount = 5 - similarWorks.size();
                for (int i = 0; i < Math.min(neededCount, latestWorks.size()); i++) {
                    similarWorks.add(latestWorks.get(i));
                }
            }

            // 3. 限制返回数量（最多5个）
            if (similarWorks.size() > 5) {
                similarWorks = similarWorks.subList(0, 5);
            }

            return ApiResponse.success(similarWorks);
        } catch (Exception e) {
            return ApiResponse.error("获取相似作品失败: " + e.getMessage());
        }
    }

    /**
     * 将任务保存为作品
     *
     * @param task 任务对象
     * @param title 作品标题
     * @param description 作品描述
     * @param isPublic 是否公开
     * @return API响应
     */
    @Transactional
    public ApiResponse<Void> createWorkFromTask(StyleTask task, String title, String description, boolean isPublic) {
        try {
            // 创建作品对象
            Work work = new Work();
            work.setTitle(title);
            work.setDescription(description);
            work.setUserId(task.getUserId());

            // 从任务的styleIds中提取第一个风格ID作为作品的风格ID
            if (task.getStyleIds() != null && !task.getStyleIds().isEmpty()) {
                work.setStyleId(task.getStyleIds());
            }

            // 设置原始图片和结果图片
            work.setOriginalImage(task.getImageUrl());
            work.setResultImage(task.getResultUrl());

            // 设置是否公开
            work.setIsPublic(isPublic ? 1 : 0);

            // 设置默认值
            work.setLikeCount(0);
            work.setCommentCount(0);
            work.setViewCount(0);
            work.setCreateTime(new Date());
            work.setUpdateTime(new Date());
            work.setStatus(1); // 1:正常, 0:删除

            // 插入作品
            workMapper.insert(work);

            // 如果有风格ID，增加风格使用次数
            if (work.getStyleId() != null) {
                List<Long> styleIds = new ArrayList<>();
                String[] styleIdArray = work.getStyleId().split(",");
                for (String id : styleIdArray) {
                    try {
                        styleMapper.incrementUseCount(Long.valueOf(id));
                    } catch (NumberFormatException e) {
                        throw new BusinessException("风格ID格式不正确: " + id);
                    }
                }

            }

            // 创建新作品通知（如果是公开作品）
            if (isPublic) {
                notificationService.createNewWorkNotification(work.getId(), title, task.getUserId());
            }

            return ApiResponse.success(null);
        } catch (Exception e) {
            throw new BusinessException("保存作品失败: " + e.getMessage());
        }
    }

    /**
     * 生成分享海报
     *
     * @param data 分享参数
     * @return API响应，返回海报URL
     */
    public ApiResponse<String> generateSharePoster(SharePosterRequest data) {
        try {
            // 检查作品是否存在
            Work work = workMapper.findById(data.getArtworkId());
            if (work == null) {
                throw new BusinessException("作品不存在");
            }

            // 生成分享链接
            String shareLink = generateShareLink(work.getId());

            // 生成二维码
            String qrCodePath = generateQRCode(shareLink);

            // 生成海报
            String posterUrl = generatePoster(work, qrCodePath);

            return ApiResponse.success(posterUrl);
        } catch (Exception e) {
            throw new BusinessException("生成分享海报失败: " + e.getMessage());
        }
    }

    /**
     * 生成分享链接
     *
     * @param workId 作品ID
     * @return 分享链接
     */
    private String generateShareLink(Long workId) {
        // 这里应该根据实际前端页面路由生成分享链接
        // 例如: https://your-domain.com/detail?id=123
        return "https://your-domain.com/detail?id=" + workId;
    }

    /**
     * 生成二维码
     *
     * @param content 二维码内容
     * @return 二维码图片路径
     */
    private String generateQRCode(String content) {
        try {
            // 创建临时文件保存二维码
            File tempFile = File.createTempFile("qrcode_", ".png");

            // 使用ZXing库生成二维码
            com.google.zxing.qrcode.QRCodeWriter qrCodeWriter = new com.google.zxing.qrcode.QRCodeWriter();
            com.google.zxing.common.BitMatrix bitMatrix = qrCodeWriter.encode(
                content,
                com.google.zxing.BarcodeFormat.QR_CODE,
                300,
                300
            );

            // 将二维码写入文件
            BufferedImage qrImage = new BufferedImage(
                300,
                300,
                BufferedImage.TYPE_INT_RGB
            );

            for (int x = 0; x < 300; x++) {
                for (int y = 0; y < 300; y++) {
                    qrImage.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
                }
            }

            javax.imageio.ImageIO.write(qrImage, "PNG", tempFile);

            // 返回临时文件路径
            return tempFile.getAbsolutePath();
        } catch (Exception e) {
            throw new BusinessException("生成二维码失败: " + e.getMessage());
        }
    }

    /**
     * 生成海报
     *
     * @param work 作品信息
     * @param qrCodePath 二维码图片路径
     * @return 海报URL
     */
    private String generatePoster(Work work, String qrCodePath) {
        try {
            // 创建临时文件保存海报
            File tempFile = File.createTempFile("poster_", ".png");

            // 加载原始图片和结果图片
            BufferedImage originalImage = loadImage(work.getOriginalImage());
            BufferedImage resultImage = loadImage(work.getResultImage());
            BufferedImage qrCodeImage = loadImage(qrCodePath);

            // 创建海报画布 (宽度: 1200px, 高度: 根据内容计算)
            int posterWidth = 1200;
            int imageWidth = (posterWidth - 60) / 2; // 两张图片宽度相等，中间留10px间距，两边各留20px边距
            int imageHeight = imageWidth * originalImage.getHeight() / originalImage.getWidth();
            int padding = 40;
            int textHeight = 200; // 文字区域高度
            int posterHeight = padding + imageHeight + padding + textHeight + padding;

            BufferedImage posterImage = new BufferedImage(
                posterWidth,
                posterHeight,
                BufferedImage.TYPE_INT_RGB
            );

            // 创建画笔
            Graphics2D g2d = posterImage.createGraphics();

            // 设置背景色
            g2d.setColor(Color.WHITE);
            g2d.fillRect(0, 0, posterWidth, posterHeight);

            // 绘制原始图片（左侧）
            g2d.drawImage(
                originalImage,
                padding,
                padding,
                imageWidth,
                imageHeight,
                null
            );

            // 绘制结果图片（右侧）
            g2d.drawImage(
                resultImage,
                padding + imageWidth + 20, // 左侧图片宽度 + 左边距 + 10px间距
                padding,
                imageWidth,
                imageHeight,
                null
            );

            // 绘制分割线
            g2d.setColor(Color.LIGHT_GRAY);
            g2d.drawLine(
                padding,
                padding + imageHeight + padding / 2,
                posterWidth - padding,
                padding + imageHeight + padding / 2
            );

            // 设置文字样式
            g2d.setColor(Color.BLACK);
            g2d.setFont(new Font("微软雅黑", Font.BOLD, 24));

            // 绘制标题
            g2d.drawString(
                work.getTitle() != null ? work.getTitle() : "AI风格重绘作品",
                padding,
                padding + imageHeight + padding + 40
            );

            // 绘制描述
            g2d.setFont(new Font("微软雅黑", Font.PLAIN, 18));
            g2d.drawString(
                work.getDescription() != null ? work.getDescription() : "扫描二维码查看更多精彩作品",
                padding,
                padding + imageHeight + padding + 80
            );

            // 绘制二维码
            g2d.drawImage(
                qrCodeImage,
                posterWidth - padding - 120,
                posterHeight - padding - 120,
                120,
                120,
                null
            );

            // 绘制二维码提示文字
            g2d.setFont(new Font("微软雅黑", Font.PLAIN, 14));
            g2d.drawString(
                "扫码查看",
                posterWidth - padding - 120 + 30,
                posterHeight - padding - 130
            );

            // 释放资源
            g2d.dispose();

            // 将海报写入文件
            javax.imageio.ImageIO.write(posterImage, "PNG", tempFile);

            // 上传海报到OSS
            String posterPath = ossService.uploadFile(tempFile, "posters");

            // 删除临时文件
            tempFile.delete();
            new File(qrCodePath).delete();

            return posterPath;
        } catch (Exception e) {
            throw new BusinessException("生成海报失败: " + e.getMessage());
        }
    }

    /**
     * 加载图片
     *
     * @param imagePath 图片路径
     * @return 图片对象
     */
    private BufferedImage loadImage(String imagePath) throws Exception {
        // 如果是OSS路径，先下载到本地
        if (imagePath.startsWith("http")) {
            URL url = new URL(imagePath);
            return javax.imageio.ImageIO.read(url);
        } else {
            return javax.imageio.ImageIO.read(new File(imagePath));
        }
    }

    /**
     * 下载所有作品结果图片并上传到OSS
     *
     * 此方法会获取所有公开的作品，下载它们的结果图片，
     * 然后将图片上传到阿里云OSS，并更新数据库中的图片URL地址
     *
     * @return API响应，包含处理结果信息
     */
    @Transactional
    public ApiResponse<String> downloadAndUploadResultImage() {
        try {
            // 获取所有公开的作品
            List<Work> publicWorks = workMapper.findPublic();
            if (publicWorks == null || publicWorks.isEmpty()) {
                return ApiResponse.error("没有找到公开的作品");
            }

            int successCount = 0;
            int failCount = 0;
            StringBuilder resultInfo = new StringBuilder();

            // 遍历所有作品，处理每一个作品的结果图片
            for (Work work : publicWorks) {
                try {
                    // 检查结果图片URL是否存在
                    String resultImageUrl = work.getResultImage();
                    if (resultImageUrl == null || resultImageUrl.isEmpty()) {
                        resultInfo.append("作品ID ").append(work.getId()).append(" 的结果图片URL不存在\n");
                        failCount++;
                        continue;
                    }

                    // 下载图片
                    File tempFile = null;
                    try {
                        // 创建临时文件
                        String fileExtension = "jpg";
                        tempFile = File.createTempFile("work_result_", "." + fileExtension);

                        // 下载图片到临时文件
                        URL url = new URL(resultImageUrl);
                        try (InputStream inputStream = url.openStream()) {
                            java.nio.file.Files.copy(
                                inputStream,
                                tempFile.toPath(),
                                java.nio.file.StandardCopyOption.REPLACE_EXISTING
                            );
                        }

                        // 上传图片到OSS
                        String newImageUrl = ossService.uploadFile(tempFile, "works");

                        // 更新数据库
                        workMapper.updateResultImage(work.getId(), newImageUrl);

                        successCount++;
                        resultInfo.append("作品ID ").append(work.getId()).append(" 处理成功，新URL: ").append(newImageUrl).append("\n");
                    } finally {
                        // 清理临时文件
                        if (tempFile != null && tempFile.exists()) {
                            tempFile.delete();
                        }
                    }
                } catch (Exception e) {
                    // 记录单个作品处理失败的信息
                    failCount++;
                    resultInfo.append("作品ID ").append(work.getId()).append(" 处理失败: ").append(e.getMessage()).append("\n");
                }
            }

            // 返回处理结果
            String resultMessage = "处理完成。成功: " + successCount + ", 失败: " + failCount + "\n" + resultInfo.toString();
            return ApiResponse.success(resultMessage);
        } catch (Exception e) {
            // 记录整体处理失败的信息
            e.printStackTrace();
            return ApiResponse.error("批量处理图片失败: " + e.getMessage());
        }
    }

    /**
     * 获取文件扩展名
     *
     * @param url 文件URL
     * @return 扩展名
     */
    private String getFileExtension(String url) {
        // 移除URL参数
        String cleanUrl = url;
        int queryIndex = url.indexOf('?');
        if (queryIndex > 0) {
            cleanUrl = url.substring(0, queryIndex);
        }

        // 获取文件名
        int lastSlashIndex = cleanUrl.lastIndexOf('/');
        String filename = (lastSlashIndex >= 0) ? cleanUrl.substring(lastSlashIndex + 1) : cleanUrl;

        // 获取扩展名
        int dotIndex = filename.lastIndexOf('.');
        if (dotIndex >= 0) {
            return filename.substring(dotIndex + 1).toLowerCase();
        }

        // 默认返回jpg
        return "jpg";
    }

    /**
     * 获取当前用户ID
     *
     * @return 用户ID
     */
    private Long getCurrentUserId() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Object principal = authentication.getPrincipal();

            // 从自定义UserDetails中获取用户ID
            if (principal instanceof com.styletransfer.security.CustomUserDetailsService.CustomUserDetails) {
                return ((com.styletransfer.security.CustomUserDetailsService.CustomUserDetails) principal).getUserId();
            }

            // 尝试从请求属性中获取用户ID
            javax.servlet.http.HttpServletRequest request =
                    ((org.springframework.web.context.request.ServletRequestAttributes)
                            org.springframework.web.context.request.RequestContextHolder.getRequestAttributes()).getRequest();
            Object userId = request.getAttribute("userId");
            if (userId != null) {
                return (Long) userId;
            }

            throw new RuntimeException("无法获取用户ID");
        } catch (Exception e) {
            throw new RuntimeException("获取用户ID失败: " + e.getMessage());
        }
    }

    /**
     * 检查当前用户是否为管理员
     *
     * @return 是否为管理员
     */
    private boolean isAdmin() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication.getAuthorities().stream()
                .anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"));
    }
}
